package com.tensquare.article.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import com.tensquare.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private IdWorker idWorker;





    public List<Article> findAll(){
        List<Article> articles = articleDao.selectList(null);
        return articles;
    }


    public Article findById(String articleId) {
        Article article = articleDao.selectById(articleId);
        return article;
    }

    @Transactional
    public void add(Article article) {
        //使用分布式id生成器
        article.setId(idWorker.nextId()+"");


        //初始化数据
        article.setVisits(0);
        article.setThumbup(0);
        article.setComment(0);

        articleDao.insert(article);


    }

    @Transactional
    public void update(Article article) {

        articleDao.updateById(article);
    }

    @Transactional
    public void delete(String id) {
        articleDao.deleteById(id);
    }

    public Page search(Map<String,Object> map, Integer page, Integer size) {
        //设置查询条件
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        Set<String> keySet = map.keySet();
        for (String key:keySet) {
            if (map.get(key)!= null){
                wrapper.eq(key,map.get(key));
            }
            //wrapper.eq(map.get(key) !=null,key,map.get(key));
        }

        //设置分页参数
        Page<Article> pageData = new Page<>(page,size);

        //执行查询
        //第一个是分页参数，第二个是查询条件
        IPage<Article> articleIPage = articleDao.selectPage(pageData, wrapper);
        List<Article> list = (List)articleIPage;
        pageData.setRecords(list);
        //返回
        return pageData;

    }
}
